Inorder Successor in BST

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
  12. if (p.right != null) {
  13. return getMin(p.right);
  14. }
  15. TreeNode succ = null;
  16. while (root != null) {
  17. if (root.val <= p.val) {
  18. root = root.right;
  19. } else {
  20. succ = root;
  21. root = root.left;
  22. }
  23. }
  24. return succ;
  25. }
  26. TreeNode getMin(TreeNode p) {
  27. while (p.left != null) {
  28. p = p.left;
  29. }
  30. return p;
  31. }
  32. }